package main

import (
	"context"
	pb "fgo/advance/other/discovery/go-grpc/api"
	"fgo/advance/other/discovery/go-grpc/balancer"
	"flag"
	"github.com/g4zhuj/grpc-wrapper/config"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/resolver"
	"time"
)

var (
	svcName       string
	etcdEndpoints string
)

func init() {
	flag.StringVar(&svcName, "service", "hello_service", "service name")
	flag.StringVar(&etcdEndpoints, "endpoints", "http://127.0.0.1:2379", "etcd endpoints")
}

func main() {
	flag.Parse()

	// set zap logger
	logcfg := config.LoggerConfig{}
	grpclog.SetLoggerV2(logcfg.NewLogger())

	// register
	r := balancer.NewResolver(etcdEndpoints)
	resolver.Register(r)

	// 初始化客户端连接
	conn, err := grpc.Dial(r.Scheme()+"://author/"+svcName, grpc.WithBalancerName("round_robin"), grpc.WithInsecure())
	if err != nil {
		grpclog.Fatal(err)
	}

	client := pb.NewHelloServiceClient(conn)
	for {
		resp, err := client.Echo(context.Background(), &pb.Payload{Data: "hello"}, grpc.FailFast(true))
		if err != nil {
			grpclog.Fatal(err)
		} else {
			grpclog.Info(resp)
		}

		<-time.After(time.Second)
	}
}
